<template>
	<view class="category-container">
		<JNavBar bgImage>
			<template #left>
				<view class="search-wrap">
					<text>分类</text>
					<JSearch></JSearch>
				</view>
			</template>
		</JNavBar>

		<!-- 一级分类 -->
		<JCategoryLevelOne :categoryList="categoryLevelOneList" :selectedItem="selectedCategoryOneItem" @category-change="handleCategoryOneChange" />
		<!-- 二级分类 -->
		<view class="container">
			<!-- 侧边分类 -->
			<JCategoryLevelTwo :categoryList="categoryLevelTwoList" :selectedItem="selectedCategoryTwoItem" @category-change="handleCategoryTwoChange" />

			<!-- 商品筛选和列表 -->
			<view class="categoryGoodsList">
				<!-- 筛选栏 -->
				<JCategoryFilter 
					:filterList="filterList" 
					:selectedItem="selectedFilterItem" 
					:maxVisibleItems="5"
					@filter-change="handleFilterChange" 
				/>
				<JGoodsFilter />
				<!-- 商品列表滚动区域 -->
				<scroll-view class="goods-scroll" scroll-y>
					<!-- 商品列表内容 -->
					<JGoodsList 
						:goodsList="goodsList"
						:hasMore="hasMore"
						:loading="loading"
						@goodsClick="handleGoodsClick"
						@loadMore="handleLoadMore"
						@addToCartSuccess="handleAddToCartSuccess"
						@addToCartError="handleAddToCartError"
					/>
				</scroll-view>
			</view>
		</view>
	</view>
</template>

<script>
export default {
	data() {
		return {
			categoryLevelOneList: [
				{ name: '推荐', icon: 'https://xianlian.e88u.com/Upload/11/pic/20251006100617_6809.png' },
				{ name: '蔬菜', icon: 'https://xianlian.e88u.com/Upload/11/pic/20251006100617_6809.png' },
				{ name: '水果', icon: 'https://xianlian.e88u.com/Upload/11/pic/20251006100617_6809.png' },
				{ name: '肉类', icon: 'https://xianlian.e88u.com/Upload/11/pic/20251006100617_6809.png' },
				{ name: '海鲜', icon: 'https://xianlian.e88u.com/Upload/11/pic/20251006100617_6809.png' },
				{ name: '调料', icon: 'https://xianlian.e88u.com/Upload/11/pic/20251006100617_6809.png' },
				{ name: '粮油', icon: 'https://xianlian.e88u.com/Upload/11/pic/20251006100617_6809.png' },
				{ name: '饮料', icon: 'https://xianlian.e88u.com/Upload/11/pic/20251006100617_6809.png' },
				{ name: '乳制品', icon: 'https://xianlian.e88u.com/Upload/11/pic/20251006100617_6809.png' },
				{ name: '豆制品', icon: 'https://xianlian.e88u.com/Upload/11/pic/20251006100617_6809.png' }
			],
			selectedCategoryOneItem: { name: '推荐', icon: 'https://xianlian.e88u.com/Upload/11/pic/20251006100617_6809.png' },
			categoryLevelTwoList: [
				{ name: '推荐' },
				{ name: '蔬菜各种文字' },
				{ name: '水果' },
				{ name: '肉类' },
				{ name: '海鲜' },
				{ name: '调料' },
				{ name: '粮油' },
				{ name: '饮料' }
			],
			selectedCategoryTwoItem: {},

			// 筛选相关
			filterList: [
				{ name: '全部' },
				{ name: '爆品' },
				{ name: '其他苹果' },
				{ name: '嘎啦' },
				{ name: '山东富士' },
				{ name: '花牛' },
				{ name: '阿克苏' },
				{ name: '冰糖心' },
				{ name: '洛川富士' },
				{ name: '苹果礼盒' },
				{ name: '黄元帅' },
				{ name: '奶油富士' },
				{ name: '国光' },
				{ name: '寒富' },
				{ name: '红玫瑰' }
			],
			selectedFilterItem: {},
			
			// 商品列表相关
			goodsList: [],
			hasMore: true,
			loading: false
		};
	},
	methods: {
		// 处理一级分类变化（从组件接收事件）
		handleCategoryOneChange(item, index) {
			this.selectedCategoryOneItem = item;
			console.log('当前选中的一级分类:', {
				name: item.name,
				icon: item.icon,
				index: index
			});

			// 根据选中的一级分类更新二级分类数据
			this.updateCategoryTwoList(item);
		},

		// 根据一级分类更新二级分类数据
		updateCategoryTwoList(categoryOne) {
			// 模拟根据一级分类获取对应的二级分类数据
			const categoryTwoMap = {
				推荐: [{ name: '热门推荐' }, { name: '新品上架' }, { name: '特价商品' }, { name: '精选好物' }],
				蔬菜: [{ name: '叶菜类' }, { name: '根茎类' }, { name: '瓜果类' }, { name: '菌菇类' }],
				水果: [{ name: '苹果' }, { name: '香蕉' }, { name: '橙子' }, { name: '葡萄' }],
				肉类: [{ name: '猪肉' }, { name: '牛肉' }, { name: '羊肉' }, { name: '鸡肉' }],
				海鲜: [{ name: '鱼类' }, { name: '虾类' }, { name: '蟹类' }, { name: '贝类' }],
				调料: [{ name: '食用油' }, { name: '调味料' }, { name: '香料' }, { name: '酱料' }],
				粮油: [{ name: '大米' }, { name: '面粉' }, { name: '杂粮' }, { name: '面条' }],
				饮料: [{ name: '果汁' }, { name: '茶类' }, { name: '咖啡' }, { name: '功能饮料' }],
				乳制品: [{ name: '牛奶' }, { name: '酸奶' }, { name: '奶酪' }, { name: '黄油' }],
				豆制品: [{ name: '豆腐' }, { name: '豆浆' }, { name: '豆干' }, { name: '腐竹' }]
			};

			// 更新二级分类数据
			this.categoryLevelTwoList = categoryTwoMap[categoryOne.name] || [{ name: '暂无分类' }];

			// 重置二级分类选中状态
			this.selectedCategoryIndex = 0;

			console.log('更新二级分类数据:', this.categoryLevelTwoList);
		},
		// 处理二级分类变化（从组件接收事件）
		handleCategoryTwoChange(item, index) {
			this.selectedCategoryTwoItem = item;
			console.log('选择二级分类:', item, '索引:', index);
		},
		// 处理筛选条件变化（从组件接收事件）
		handleFilterChange(item, index) {
			this.selectedFilterItem = item;
			console.log('选择筛选条件:', item, '索引:', index);
		},
		
		// 处理商品点击
		handleGoodsClick(goods) {
			console.log('跳转到商品详情', goods);
			uni.navigateTo({
				url: `/pages/goods/goods?id=${goods.id}`
			});
		},
		
		// 处理加载更多
		handleLoadMore() {
			if (this.loading) return;
			
			this.loading = true;
			console.log('加载更多商品');
			
			// 模拟加载延迟
			setTimeout(() => {
				// 模拟添加更多商品数据
				const moreGoods = this.generateMockGoods(5);
				this.goodsList = [...this.goodsList, ...moreGoods];
				this.loading = false;
				
				// 模拟没有更多数据的情况
				if (this.goodsList.length > 20) {
					this.hasMore = false;
				}
			}, 1000);
		},
		
		// 处理添加到购物车成功
		handleAddToCartSuccess(item) {
			console.log('商品已添加到购物车:', item);
			uni.showToast({
				title: '已添加到购物车',
				icon: 'success',
				duration: 1500
			});
		},
		
		// 处理添加到购物车失败
		handleAddToCartError(error) {
			console.error('添加购物车失败:', error);
			uni.showToast({
				title: '添加失败，请重试',
				icon: 'none',
				duration: 1500
			});
		},
		
		// 生成模拟商品数据
		generateMockGoods(count = 10) {
			const goods = [];
			for (let i = 0; i < count; i++) {
				goods.push({
					id: `goods_${Date.now()}_${i}`,
					name: `商品名称${i + 1} - 优质商品描述`,
					image: `https://picsum.photos/300/300?random=${i}`,
					price: (Math.random() * 100 + 10).toFixed(2),
					originalPrice: (Math.random() * 150 + 50).toFixed(2),
					weight: `${(Math.random() * 5 + 1).toFixed(1)}kg`,
					sales: Math.floor(Math.random() * 1000) + 100,
					stock: Math.floor(Math.random() * 100) + 10,
					minQuantity: Math.floor(Math.random() * 10) + 1,
					unit: '件',
					shopName: `店铺${i + 1}`,
					shopLink: `/pages/shop/shop?id=${i + 1}`,
					description: `这是商品${i + 1}的详细描述信息`,
					badges: this.generateBadges(),
					labels: this.generateLabels()
				});
			}
			return goods;
		},
		
		// 生成商品标签
		generateBadges() {
			const badgeTypes = ['hot', 'new', 'sale', 'limit'];
			const badgeTexts = {
				hot: '热销',
				new: '新品',
				sale: '特价',
				limit: '限购'
			};
			
			const badges = [];
			const randomCount = Math.floor(Math.random() * 2) + 1;
			const selectedTypes = badgeTypes.sort(() => 0.5 - Math.random()).slice(0, randomCount);
			
			selectedTypes.forEach(type => {
				if (Math.random() > 0.5) {
					badges.push({
						type: type,
						text: badgeTexts[type]
					});
				}
			});
			
			return badges;
		},
		
		// 生成商品标签
		generateLabels() {
			const labelTypes = ['limit', 'min', 'multiple', 'special', 'discount'];
			const labelTexts = {
				limit: '限量',
				min: '起订',
				multiple: '倍数',
				special: '特供',
				discount: '折扣'
			};
			
			const labels = [];
			const randomCount = Math.floor(Math.random() * 3) + 1;
			const selectedTypes = labelTypes.sort(() => 0.5 - Math.random()).slice(0, randomCount);
			
			selectedTypes.forEach(type => {
				if (Math.random() > 0.6) {
					labels.push({
						type: type,
						text: labelTexts[type]
					});
				}
			});
			
			return labels;
		}
	},
	
	onLoad() {
		// 页面加载时初始化商品数据
		this.initGoodsData();
	},
	
	// 初始化商品数据
	initGoodsData() {
		// 生成初始商品数据
		this.goodsList = this.generateMockGoods(10);
		console.log('初始化商品数据:', this.goodsList);
	}
};
</script>

<style lang="less">
@categoryLevelOneHeight: 160rpx;
@categoryLevelTwoWidth: 160rpx;
@basecolor: #246ef9;
.category-container {
	box-sizing: border-box;
	/* 使用flex布局确保容器填满屏幕 */
	display: flex;
	flex-direction: column;
	height: 100vh;
	/* #ifdef H5 */
	height: calc(100vh - (var(--window-top) + var(--status-bar-height) + var(--window-bottom))); /* H5端减去导航栏高度 */
	/* 确保H5端没有滚动条 */
	overflow: hidden;
	/* #endif */
	/* #ifdef MP-WEIXIN */
	height: calc(100vh - env(safe-area-inset-top) - env(safe-area-inset-bottom));
	/* #endif */
	.search-wrap {
		display: flex;
		align-items: center;
		justify-content: space-between;
		padding-right: 100px;
		text {
			font-size: 36rpx;
			font-weight: 600;
			color: #333;
			color: #fff;
			line-height: 1;
			margin-right: 20rpx;
			white-space: nowrap;
		}
	}
	.container {
		display: flex;
		background: #fff;
		width: 100%;
		box-sizing: border-box;
		/* 使用flex: 1自动填充剩余空间，避免滚动条 */
		flex: 1;
		overflow: hidden;
		/* 确保没有额外的边距 */
		margin: 0;
		padding: 0;

		.categoryGoodsList {
			flex: 1;
			overflow: hidden;
			display: flex;
			flex-direction: column;

			// 商品列表滚动区域
			.goods-scroll {
				flex: 1;
				// .bor();
				height: 100%;
				overflow: hidden;
			}
		}
	}
}
</style>
